package org.dromara.bean.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.bean.domain.HisDep;
import org.dromara.bean.domain.HisRegistration;
import org.dromara.bean.domain.SysOss;
import org.dromara.bean.mapper.HisDepMapper;
import org.dromara.bean.mapper.HisRegistrationMapper;
import org.dromara.bean.mapper.SysOssMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.tenant.helper.TenantHelper;
import org.springframework.stereotype.Service;
import org.dromara.bean.domain.bo.HisDoctorBo;
import org.dromara.bean.domain.vo.HisDoctorVo;
import org.dromara.bean.domain.HisDoctor;
import org.dromara.bean.mapper.HisDoctorMapper;
import org.dromara.bean.service.IHisDoctorService;

import java.util.*;

/**
 * 医生Service业务层处理
 *
 * @author Lion Li
 * @date 2024-10-18
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class HisDoctorServiceImpl implements IHisDoctorService {

    private final HisDoctorMapper baseMapper;
    private final HisRegistrationMapper registrationMapper;
    private final HisDepMapper depMapper;
    private final SysOssMapper sysOssMapper;
    /**
     * 查询医生
     *
     * @param id 主键
     * @return 医生
     */
    @Override
    public HisDoctorVo queryById(Long id) {
        HisDoctorVo hisDoctorVo = baseMapper.selectDoctorById(id);
        if (hisDoctorVo == null) {
            throw new RuntimeException("医生不存在");
        }

        // 1. 统计挂号数并更新virtuals
        Long regCount = registrationMapper.selectCount(
            new LambdaQueryWrapper<HisRegistration>()
                .eq(HisRegistration::getDoctorId, hisDoctorVo.getId())
        );
        hisDoctorVo.setVirtuals(hisDoctorVo.getVirtuals() + regCount.intValue());

        // 2. 处理科室ID，查询对应的科室名称
        String depIdStr = hisDoctorVo.getDepId();
        if (StringUtils.isBlank(depIdStr)) {
            hisDoctorVo.setTitle(""); // 无科室ID时设为空
            return hisDoctorVo;
        }

        // 分割科室ID字符串为数组
        String[] depIds = depIdStr.split(",");
        Set<Long> depIdSet = new HashSet<>();
        for (String depId : depIds) {
            try {
                depIdSet.add(Long.parseLong(depId.trim())); // 转换为Long并去重
            } catch (NumberFormatException e) {
                log.warn("无效的科室ID格式：{}", depId);
            }
        }

        // 批量查询科室名称（减少数据库交互）
        Map<Long, String> depIdToTitleMap = new HashMap<>();
        if (!depIdSet.isEmpty()) {
            List<HisDep> deps = depMapper.selectList(
                new LambdaQueryWrapper<HisDep>()
                    .in(HisDep::getId, depIdSet)
                    .select(HisDep::getId, HisDep::getTitle)
            );
            deps.forEach(dep -> depIdToTitleMap.put(dep.getId(), dep.getTitle()));
        }

        // 按原始ID顺序拼接科室名称
        List<String> depTitles = new ArrayList<>();
        for (String depId : depIds) {
            try {
                Long idLong = Long.parseLong(depId.trim());
                depTitles.add(depIdToTitleMap.getOrDefault(idLong, "未知科室"));
            } catch (NumberFormatException e) {
                depTitles.add("无效科室ID");
            }
        }

        hisDoctorVo.setTitle(String.join(",", depTitles));
        SysOss oss = sysOssMapper.selectById(hisDoctorVo.getPhoto());
        hisDoctorVo.setPhotoUrl(oss != null ? oss.getUrl() : null);
        return hisDoctorVo;
    }

    /**
     * 分页查询医生列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 医生分页列表
     */
    @Override
    public TableDataInfo<HisDoctorVo> queryPageList(HisDoctorBo bo, PageQuery pageQuery) {
        QueryWrapper<HisDoctor> lqw = buildQueryWrapper(bo);
        Page<HisDoctorVo> result = baseMapper.selectDoctorVoPage(pageQuery.build(), lqw);

        Set<Long> depIdSet = new HashSet<>();
        for (HisDoctorVo vo : result.getRecords()) {
            String depId = vo.getDepId();
            if (StringUtils.isNotBlank(depId)) {
                String[] ids = depId.split(",");
                for (String id : ids) {
                    depIdSet.add(Long.parseLong(id.trim()));
                }
            }
        }

        // 批量查询科室ID
        Map<Long, String> depIdToTitleMap = new HashMap<>();
        if (!depIdSet.isEmpty()) {
            List<HisDep> deps = depMapper.selectList(
                new LambdaQueryWrapper<HisDep>()
                    .in(HisDep::getId, depIdSet)
                    .select(HisDep::getId, HisDep::getTitle)
            );
            for (HisDep dep : deps) {
                depIdToTitleMap.put(dep.getId(), dep.getTitle());
            }
        }

        result.getRecords().forEach(vo -> {
            try {
                SysOss oss = sysOssMapper.selectById(vo.getPhoto());
                vo.setPhotoUrl(oss != null ? oss.getUrl() : null);
            } catch (Exception e) {
                log.error("获取photoUrl失败，photo={}", vo.getPhoto(), e);
                vo.setPhotoUrl(null);
            }

            Long regCount = registrationMapper.selectCount(
                new LambdaQueryWrapper<HisRegistration>().eq(HisRegistration::getDoctorId, vo.getId())
            );
            vo.setVirtuals(vo.getVirtuals() + regCount.intValue());

            // 处理科室名称
            String depId = vo.getDepId();
            if (StringUtils.isBlank(depId)) {
                vo.setTitle(""); // 无科室ID时设为空
                return;
            }

            String[] ids = depId.split(",");
            List<String> titles = new ArrayList<>();
            for (String id : ids) {
                Long depIdLong = Long.parseLong(id.trim());
                titles.add(depIdToTitleMap.getOrDefault(depIdLong, "未知科室"));
            }
            vo.setTitle(String.join(",", titles));
        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的医生列表
     *
     * @param bo 查询条件
     * @return 医生列表
     */
    @Override
    public List<HisDoctorVo> queryList(HisDoctorBo bo) {
        QueryWrapper<HisDoctor> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper<HisDoctor> buildQueryWrapper(HisDoctorBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<HisDoctor> lqw = new QueryWrapper<>();
        lqw.like(StringUtils.isNotBlank(bo.getName()), "h.name", bo.getName());
//        lqw.eq(bo.getDepId() != null, "h.dep_id", bo.getDepId());
//        lqw.eq(StringUtils.isNotBlank(bo.getLevel()), "h.level", bo.getLevel());
        lqw.eq("h.del_flag", 0);
        lqw.orderByDesc("h.create_time");
        String orderPrice = bo.getOrderPrice();
        if (StringUtils.isNotBlank(orderPrice)) {
            if ("asc".equalsIgnoreCase(orderPrice)) {
                lqw.orderByAsc("h.price");
            } else if ("desc".equalsIgnoreCase(orderPrice)) {
                lqw.orderByDesc("h.price");
            }
        }
        if (bo.getDepId() != null) {
            String targetDepId = bo.getDepId().toString();
            lqw.and(qw -> qw
                .like("dep_id", "," + targetDepId + ",")
                .or().likeRight("dep_id", targetDepId + ",")
                .or().likeLeft("dep_id", "," + targetDepId)
                .or().eq("dep_id", targetDepId)
            );
        }
        return lqw;
    }

    /**
     * 新增医生
     *
     * @param bo 医生
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HisDoctorBo bo) {
        HisDoctor add = MapstructUtils.convert(bo, HisDoctor.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改医生
     *
     * @param bo 医生
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HisDoctorBo bo) {
        HisDoctor update = MapstructUtils.convert(bo, HisDoctor.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HisDoctor entity) {
        //判断医生科室是否存在
        if (entity.getDepId() != null) {
            for (String s : entity.getDepId().split(",")) {
                HisDep hisDep = depMapper.selectById(Integer.parseInt(s));
                if (hisDep == null) {
                    throw new RuntimeException("医生科室不存在,请重新选择医生科室");
                }
            }
        }
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除医生信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
